/*
 * File Name : ProductListComponent.js
 *
 */
import Bb from 'backbone';
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';

import MessageView from '../../../base/views/MessageView.js';

import CategoriesComponent from '../categories/CategoriesComponent.js';
import ProductTable  from './ProductTable.js';
import ProductFilterForm from './ProductFilterForm.js';
import PagerWidget from '../../../widgets/PagerWidget.js';
import ButtonWidget from "../../../widgets/ButtonWidget";

const template = require('./templates/ProductListComponent.mustache');

const ProductListComponent = Mn.View.extend({
    /*
     * A list view : filter + list + category component
     *
     * takes 2 parameters:
     *
     *  collection
     *  filter_model
     */
    template: template,
    regions: {
        categoryContainer: '.category-container',
        filters: '.search_filters',
        messageContainer: {el: ".message-container", replaceElement: true},
        pager_widget_bottom: {el: '.pager_widget_bottom', replaceElement: true},
        pager_widget_top: {el: '.pager_widget_top', replaceElement: true},
        table: ".table_container",
        export_json_button: "li.export_json_button"
    },
    ui: {
        add_button: 'button[value=add]',
        export_json_button: 'a.export_json',
        export_csv_button: 'a.export_csv',
    },
    events: {
        'click @ui.add_button': 'onAddButtonClicked',
        'click @ui.export_csv_button': 'onExportCSVButtonClicked',
    },
    // Listen to child view events
    childViewEvents: {
        'filter:submit': 'onListFilter',
        'list:filter': 'onListFilter',
        'list:navigate': 'onListNavigate',
        'model:delete': 'onModelDelete',
        'model:duplicate': 'onModelDuplicate',
        'model:edit': 'onModelEdit',
        'model:archive': 'onModelArchive',
        'navigate:itemsperpage': 'onNavigateItemsPerPage',
        'navigate:page': 'onNavigatePage',
        'export:json': "onExportJSONButtonClicked",
    },
    initialize(){
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        this.filter_model = this.facade.request('get:model', 'ui_list_filter');
        this.app = Radio.channel('app');
    },
    showFilters(){
        this.filterView = new ProductFilterForm({model: this.filter_model});
        this.showChildView('filters', this.filterView);
    },
    loadTable(){
        var serverCall = this.facade.request('get:collection:page', 'products', this.collection.state.currentPage);
        serverCall.done(this.showTable.bind(this));
        serverCall.done(this.showPagerWidgets.bind(this));
    },
    showPagerWidgets(){
        if (this.collection.length > 0){
            this.showChildView('pager_widget_top', new PagerWidget({collection: this.collection, position: 'top'}));
            this.showChildView('pager_widget_bottom', new PagerWidget({collection: this.collection, position: 'bottom'}));
        }
    },
    showTable(){
        this.filter_model.set('currentPage', this.collection.state['currentPage']);
        let view = new ProductTable({collection: this.collection});
        this.showChildView('table', view);
    },
    showCategories(){
        let collection = this.facade.request('get:collection', 'categories');
        let view = new CategoriesComponent({collection: collection});
        this.showChildView('categoryContainer', view);
    },
    showMessageView(){
       var model = new Bb.Model();
       var view = new MessageView({model: model});
       this.showChildView('messageContainer', view);
    },
    showExportJSONButton() {
        this.showChildView(
            'export_json_button',
            new ButtonWidget({
                css: "icon_only mobile",
                title: "Permet un ré-import dans " + SOFT_NAME,
                icon: "file-export",
                label: "Catalogue produits (JSON)",
                event: "export:json"
            })
        );
    },
    onRender(){
        this.showMessageView();
        this.showFilters();
        this.showCategories();
        this.loadTable();
        this.showExportJSONButton();
    },
    /* List related events */
    onNavigate(event){
        /*
         * The event target has an event-type (getPreviousPage, getNextPage
         * ...) attached that is used for the facade request
         * */
        let event_type = $(event.target).data('event-type');
        this.triggerMethod('list:navigate', event_type);
    },
    onListFilter(childView, filters){
        var serverCall = this.facade.request('get:collection:filter', 'products', filters);
        serverCall.done(this.showTable.bind(this));
        serverCall.done(this.showPagerWidgets.bind(this));
    },
    onListNavigate(event_type){
        /*
         * Launched when navigating in the list's pages
         */
        var serverCall = this.facade.request('get:collection:' + event_type, 'products');
        serverCall.done(this.showTable.bind(this));
        serverCall.done(this.showPagerWidgets.bind(this));
    },
    onNavigateItemsPerPage(items_per_page){
        var serverCall = this.facade.request('set:collection:itemsperpage', 'products', items_per_page);
        serverCall.done(this.showTable.bind(this));
        serverCall.done(this.showPagerWidgets.bind(this));
    },
    onNavigatePage(page){
        var serverCall = this.facade.request('get:collection:page', 'products', page);
        serverCall.done(this.showTable.bind(this));
        serverCall.done(this.showPagerWidgets.bind(this));
    },
    /* Add product action */
    onAddButtonClicked(){
        this.app.trigger('navigate', 'addproduct');
    },
    onModelEdit(childView){
        const modelId = childView.model.get('id');
        this.app.trigger('navigate', 'products/' + modelId);
    },
    onModelDelete(childView){
        this.app.trigger('product:delete', childView);
    },
    onModelDuplicate(childView){
        this.app.trigger('product:duplicate', childView);
    },
    onModelArchive(childView){
        this.app.trigger('product:archive', childView);
    },
    onExportCSVButtonClicked(childView){
        this.app.trigger('products:export', childView, "csv");
    },
    onExportJSONButtonClicked(childView){
        this.app.trigger('products:export', childView, "json");
    },
    templateContext() {
        return {
            json_import_url: this.config.request("get:options", 'json_import_url'),
        }
    }
});
export default ProductListComponent;
